<script setup>
import { ref, watch, inject, computed, defineEmits } from 'vue'
import documentApi from '@/apis/document'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['confirm'])

const model = defineModel()
const visible = ref(false)

const document = ref({})
const isSmallPage = inject('isSmallPage')
const loading = ref(false)
const title = computed(() => document.value.title || '内容')

const loadDocument = async () => {
  document.value = {}
  try {
    loading.value = true
    document.value = (await documentApi.page(model.value)).data
  } catch (e) {
    console.log(e)
    document.value = { title: '出错了', content: '加载失败' }
  } finally {
    loading.value = false
  }
}

const confirm = () => {
  visible.value = false
  emit('confirm')
}

const close = () => {
  model.value = ''
}

const show = (pageName) => {
  if (!pageName) {
    ElMessage.error('请先选择要查看的文档')
    return
  }
  model.value = pageName
  loadDocument()
  visible.value = true
}

defineExpose({
  show,
})
</script>

<template>
  <el-dialog
    append-to-body
    v-model="visible"
    :title="title"
    :width="isSmallPage ? '90%' : '650px'"
    @close="close"
  >
    <div class="flex flex-col max-h-[65vh] min-h-[400px]">
      <ArticleProse class="flex-1 overflow-y-auto" :content="document.content" />
      <div class="flex-1 text-center" v-if="loading">
        <FontAwesomeIcon icon="spinner" spin /><span>加载中...</span>
      </div>
      <div class="flex justify-end mt-3">
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped></style>
